//
//  AppointmentCenterViewController.m
//  customer
//
//  Created by Holothurian on 2018/11/5.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "AppointmentCenterViewController.h"
#import "SelfInfoLabelTableViewCell.h"
#import "AppointOrderDetailViewController.h"

static NSString *AppointmentCellIdentifier =  @"AppointmentCellIdentifier";
@interface AppointmentCenterViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)NSArray *keyArray;

@property (nonatomic,strong)NSMutableArray *valueArray;


@end

@implementation AppointmentCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createMainView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}

- (void)createMainView{
    if (self.selectIndex == 0||self.selectIndex == 1) {
        self.keyArray = @[@"下单时间",@"选择类型",@"联系人",@"联系电话",@"详细地址"];
    }else{
        self.keyArray = @[@"下单时间",@"项目名称",@"联系人",@"联系电话",@"详细地址"];
    }
    self.title = @"预约中心";
    UISegmentedControl *segmentControl = [[UISegmentedControl alloc]initWithItems:@[@"装修预约",@"设计预约",@"加配预约"]];
    segmentControl.selectedSegmentIndex = self.selectIndex;
    segmentControl.tintColor = [HSPublic colorWithHexString:@"333333"];
    segmentControl.backgroundColor = [UIColor whiteColor];
    [segmentControl setTitleTextAttributes:@{NSFontAttributeName:Font28} forState:UIControlStateNormal];
    [segmentControl setTitleTextAttributes:@{NSFontAttributeName:Font28} forState:UIControlStateSelected];
    [segmentControl addTarget:self action:@selector(segmentControlAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segmentControl];
    AutoWeakSelf
    [segmentControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(NAVIGATION_BAR_HEIGHT + 10);
        make.left.equalTo(weakSelf.view).offset(15);
        make.right.equalTo(weakSelf.view).offset(-15);
        make.height.mas_offset(30);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(segmentControl.mas_bottom);
        make.left.right.equalTo(weakSelf.view);
        make.height.mas_offset(F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(40));
    }];
    [self setRefreshEnabled:YES];
    [self.tableView registerClass:[SelfInfoLabelTableViewCell class] forCellReuseIdentifier:AppointmentCellIdentifier];
}

- (void)segmentControlAction:(UISegmentedControl *)segment{
    self.selectIndex = segment.selectedSegmentIndex;
    self.page = 1;
    [self.tableView.mj_header beginRefreshing];
}

- (void)loadDataList{
    if (self.selectIndex == 0||self.selectIndex == 1) {
        self.keyArray = @[@"下单时间",@"选择类型",@"联系人",@"联系电话",@"详细地址"];
    }else{
        self.keyArray = @[@"下单时间",@"项目名称",@"联系人",@"联系电话",@"详细地址"];
    }
    AutoWeakSelf
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:0];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserID)] forKey:@"member_id"];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserToken)] forKey:@"member_token"];
    [dict setObject:[NSNumber numberWithInteger:self.page] forKey:@"page"];
    
    if (self.selectIndex == 0 || self.selectIndex == 1) {
        [dict setObject:[NSString stringWithFormat:@"%ld",self.selectIndex+1] forKey:@"order_type"];//1:装修预约 2:设计预约
        [dict setObject:@"0,1" forKey:@"order_state"];//1:已预约
    }else if (self.selectIndex == 2){
        [dict setObject:@"0,1" forKey:@"order_state"];//1:已预约
    }
    if (self.page == 1) {
        [self.valueArray removeAllObjects];
        [self.dataList removeAllObjects];
    }
    [self showLoading];
    [[QYNetManager sharedManager]POST:(self.selectIndex == 2 ? kGetCustomizedOrders:kGetRenovationOrders) parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        [weakSelf endReresh];
        id resultData = responseObject[@"data"];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else if (![resultData isKindOfClass:[NSNull class]] && [resultData isKindOfClass:[NSArray class]] && [resultData count]){
            if ([responseObject[@"total"] integerValue]<10 || ([responseObject[@"total"] integerValue] == self.dataList.count)) {
                [weakSelf.tableView.mj_footer removeFromSuperview];
            }
            for (NSDictionary *dict in resultData) {
                NSMutableArray *tempArr = [NSMutableArray array];
                if (self.selectIndex == 0||self.selectIndex == 1) {
                    DecorateInsertOrderModel *model = [DecorateInsertOrderModel yy_modelWithDictionary:dict];
                    [tempArr addObject:model.create_time];
                    [tempArr addObject:model.style_name];
                    [tempArr addObject:model.contact_name];
                    [tempArr addObject:model.contact_mobile];
                    [tempArr addObject:model.address_detail];
                    [weakSelf.dataList addObject:model];
                }else{
                    CustomAddModel *model = [CustomAddModel yy_modelWithDictionary:dict];
                    [tempArr addObject:model.create_time];
                    [tempArr addObject:model.customized_name];
                    [tempArr addObject:model.contact_name];
                    [tempArr addObject:model.contact_mobile];
                    [tempArr addObject:model.address_detail];
                    [weakSelf.dataList addObject:model];
                }
                [weakSelf.valueArray addObject:tempArr];
            }
            
            [weakSelf.tableView reloadData];
            weakSelf.tableView.showEmpty = NO;
        }else if (![resultData isKindOfClass:[NSNull class]] && [resultData isKindOfClass:[NSArray class]] && [resultData count] == 0){
            [weakSelf.dataList removeAllObjects];
            weakSelf.tableView.showEmpty = YES;
            [weakSelf.tableView reloadData];
        }
    } Failure:^(NSError *error) {
        [weakSelf endReresh];
        [weakSelf hideLoading];
        weakSelf.tableView.showEmpty = YES;
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

- (void)deleteCancelOrderRequest:(NSString *)requestType OrderID:(NSString *)order_id{

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:K_UserDefault_Read(CustomerUserID)?:@"" forKey:@"member_id"];
    [dict setObject:K_UserDefault_Read(CustomerUserToken)?:@"" forKey:@"member_token"];
    [dict setObject:order_id?:@"" forKey:@"order_id"];
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:requestType parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        NSString * statusStr = [NSString stringWithFormat:@"%@",responseObject[@"status"]];
        if ([statusStr isEqualToString:@"ok"]) {
            if ([responseObject[@"data"] integerValue]) {
                [weakSelf showTipWithTitle:@"操作成功"];
                [weakSelf loadDataList];
            }else{
                [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
            }
        }else{
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showTipWithTitle:@"操作失败"];
    }];
    
}




#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if ([self.dataList count] == 0) {
        return 0;
    }
    return [self.valueArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([self.dataList count] == 0) {
        return 0;
    }
    return [(NSMutableArray *)self.valueArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ((indexPath.section < [self.valueArray count]) && (indexPath.row < [(NSMutableArray *)self.valueArray[indexPath.section] count])) {
        //懒得再写一个cell
        SelfInfoLabelTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:AppointmentCellIdentifier];
        cell.nameLabel.text = self.keyArray[indexPath.row];
        cell.nameLabel.textColor = [HSPublic colorWithHexString:@"333333"];
        cell.detailNameLabel.textColor = [HSPublic colorWithHexString:@"333333"];
        NSString *valueString = self.valueArray[indexPath.section][indexPath.row]?:@"";
        cell.detailNameLabel.text = valueString;
        cell.detailNameLabel.textAlignment = NSTextAlignmentLeft;
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, 10)];
    backView.backgroundColor = [UIColor appColor];
    return backView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, 40)];
    backView.backgroundColor = [UIColor whiteColor];
    UIButton *detailBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [detailBtn setTitle:@"查看详情" forState:UIControlStateNormal];
    [detailBtn setTitle:@"查看详情" forState:UIControlStateSelected];
    [detailBtn setTitleColor:[HSPublic colorWithHexString:@"#666666"] forState:UIControlStateNormal];
    [detailBtn setTitleColor:[HSPublic colorWithHexString:@"#666666"] forState:UIControlStateSelected];
    detailBtn.tag = section;
    detailBtn.titleLabel.font = Font(12);
    detailBtn.layer.borderWidth = 1;
    detailBtn.layer.cornerRadius = 2;
    detailBtn.layer.masksToBounds = YES;
    detailBtn.layer.borderColor = [HSPublic colorWithHexString:@"#666666"].CGColor;
    [detailBtn addTarget:self action:@selector(detailButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:detailBtn];
    [detailBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(backView).offset(-15);
        make.top.equalTo(backView).offset(5);
        make.size.mas_equalTo(CGSizeMake(80, 30));
    }];
    
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.titleLabel.font = Font(12);
    deleteBtn.layer.borderWidth = 1;
    deleteBtn.layer.cornerRadius = 2;
    deleteBtn.layer.masksToBounds = YES;
    [backView addSubview:deleteBtn];
    if (self.selectIndex == 0||self.selectIndex == 1) {
        DecorateInsertOrderModel *model = self.dataList[section];
        //删除订单
        if ([model.order_state isEqualToString:@"0"]) {
            [deleteBtn setTitle:@"删除订单" forState:UIControlStateNormal];
            [deleteBtn setTitle:@"删除订单" forState:UIControlStateSelected];
            [deleteBtn setTitleColor:[HSPublic colorWithHexString:@"D51A28"] forState:UIControlStateNormal];
            [deleteBtn setTitleColor:[HSPublic colorWithHexString:@"D51A28"] forState:UIControlStateSelected];
            deleteBtn.layer.borderColor = [HSPublic colorWithHexString:@"D51A28"].CGColor;
            deleteBtn.tag = section + 200000;
            [deleteBtn addTarget:self action:@selector(deleteButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(detailBtn.mas_left).offset(-20);
                make.top.equalTo(backView).offset(5);
                make.size.mas_equalTo(CGSizeMake(80, 30));
            }];
        }else{//取消订单
            [deleteBtn setTitle:@"取消订单" forState:UIControlStateNormal];
            [deleteBtn setTitle:@"取消订单" forState:UIControlStateSelected];
            [deleteBtn setTitleColor:[HSPublic colorWithHexString:@"#666666"] forState:UIControlStateNormal];
            [deleteBtn setTitleColor:[HSPublic colorWithHexString:@"#666666"] forState:UIControlStateSelected];
            deleteBtn.layer.borderColor = [HSPublic colorWithHexString:@"#666666"].CGColor;
            deleteBtn.tag = section + 100000;
            [deleteBtn addTarget:self action:@selector(cancelButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(detailBtn.mas_left).offset(-20);
                make.top.equalTo(backView).offset(5);
                make.size.mas_equalTo(CGSizeMake(80, 30));
            }];
        }
    }else{
        CustomAddModel *model = self.dataList[section];
        //删除订单
        if ([model.order_state isEqualToString:@"0"]) {
            [deleteBtn setTitle:@"删除订单" forState:UIControlStateNormal];
            [deleteBtn setTitle:@"删除订单" forState:UIControlStateSelected];
            [deleteBtn setTitleColor:[HSPublic colorWithHexString:@"D51A28"] forState:UIControlStateNormal];
            [deleteBtn setTitleColor:[HSPublic colorWithHexString:@"D51A28"] forState:UIControlStateSelected];
            deleteBtn.layer.borderColor = [HSPublic colorWithHexString:@"D51A28"].CGColor;
            deleteBtn.tag = section + 200000;
            [deleteBtn addTarget:self action:@selector(deleteButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(detailBtn.mas_left).offset(-20);
                make.top.equalTo(backView).offset(5);
                make.size.mas_equalTo(CGSizeMake(80, 30));
            }];
        }else{//取消订单
            [deleteBtn setTitle:@"取消订单" forState:UIControlStateNormal];
            [deleteBtn setTitle:@"取消订单" forState:UIControlStateSelected];
            [deleteBtn setTitleColor:[HSPublic colorWithHexString:@"#666666"] forState:UIControlStateNormal];
            [deleteBtn setTitleColor:[HSPublic colorWithHexString:@"#666666"] forState:UIControlStateSelected];
            deleteBtn.layer.borderColor = [HSPublic colorWithHexString:@"#666666"].CGColor;
            [deleteBtn addTarget:self action:@selector(cancelButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            deleteBtn.tag = section + 100000;
            [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(detailBtn.mas_left).offset(-20);
                make.top.equalTo(backView).offset(5);
                make.size.mas_equalTo(CGSizeMake(80, 30));
            }];
        }
    }
    
    return backView;
}

//删除订单
- (void)deleteButtonAction:(UIButton *)sender{
    NSInteger index = sender.tag - 200000;
    if (index >= [self.dataList count]) {
        return;
    }
    switch (self.selectIndex) {
        case 0:
        case 1:{
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self showLoadingTitle:@"正在删除订单..."];
                DecorateInsertOrderModel *model = self.dataList[index];
                [self deleteCancelOrderRequest:kDeleteRenovationOrder OrderID:model.order_id];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认删除订单?" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];
            
        }break;
        case 2:{
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self showLoadingTitle:@"正在删除订单..."];
                CustomAddModel *model = self.dataList[index];
                [self deleteCancelOrderRequest:kDeleteCustionizedOrder OrderID:model.order_id];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认删除订单?" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];
            
        }
        default:
            break;
    }
}

//取消订单
- (void)cancelButtonAction:(UIButton *)sender{
    NSInteger index = sender.tag - 100000;
    if (index >= [self.dataList count]) {
        return;
    }
    switch (self.selectIndex) {
        case 0:
        case 1:{
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self showLoadingTitle:@"正在取消订单..."];
                DecorateInsertOrderModel *model = self.dataList[index];
                [self deleteCancelOrderRequest:kCancelRenovationOrder OrderID:model.order_id];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认取消订单?" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];
            
        }break;
        case 2:{
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self showLoadingTitle:@"正在取消订单..."];
                CustomAddModel *model = self.dataList[index];
                [self deleteCancelOrderRequest:kCancelCustionizedOrder OrderID:model.order_id];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认取消订单?" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];
        }
        default:
            break;
    }
}

//查看详情
- (void)detailButtonEvent:(UIButton *)sender{
    NSInteger index = sender.tag;
    if (index >= [self.dataList count]) {
        return;
    }
    AppointOrderDetailViewController *orderDetail = [AppointOrderDetailViewController new];
    switch (self.selectIndex) {
        case 0:
        case 1:{
            DecorateInsertOrderModel *model = self.dataList[index];
            orderDetail.order_id = model.order_id;
        }break;
        case 2:{
            CustomAddModel *model = self.dataList[index];
            orderDetail.order_id = model.order_id;
        }
        default:
            break;
    }
    orderDetail.selectIndex = self.selectIndex;
    TAB_PUSH(self, orderDetail, YES);
    
}

- (NSArray *)keyArray{
    if (!_keyArray) {
        _keyArray = [NSArray array];
    }
    return _keyArray;
}

- (NSMutableArray *)valueArray{
    if (!_valueArray) {
        _valueArray = [NSMutableArray array];
    }
    return _valueArray;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
